package net.fornwall.eclipsecoder.actions;

import net.fornwall.eclipsecoder.preferences.EclipseCoderPlugin;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

/**
 * The action for starting the TopCoder contest applet.
 * 
 * <p>
 * <strong>Problem:</strong> TopCoder creates a
 * com.topcoder.client.contestApplet.editors.DynamicEditor$CustomLoader@13a0934
 * class loader to load in the plug-in. This can only find classes in the
 * supplied class path, giving problems with eclipse packages which is needed to
 * call back to. Best solution would be to disable/replace the custom class
 * loader and use the one provided by eclipse.
 * 
 * <p>
 * This is just a custom class loader, it is NOT set as the thread context class
 * loader, so messing with the SecurityManager does not work.
 */
public class StartAction implements IWorkbenchWindowActionDelegate {

	private static IAction theAction = new Action("Start", ImageDescriptor
			.createFromURL(Platform.getBundle(EclipseCoderPlugin.PLUGIN_ID)
					.getEntry("icons/tc_logo.gif"))) {
		{
			// PlatformUI.getWorkbench()
			// .getSharedImages().getImageDescriptor(ISharedImages.IMG_TOOL_FORWARD))
			// {
			setToolTipText("Start the TopCoder contest applet");
		}

		@Override
		public void run() {
			new StartAction().run(this);
		}
	};

	public static IAction getAction() {
		return theAction;
	}

	/**
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
	 */
	public void dispose() {
		// do nothing
	}

	/**
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
	 */
	public void init(IWorkbenchWindow window) {
		// do nothing
	}

	/**
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		getAction().setEnabled(false);
		DownloadAppletJob.runOrDownload();
	}

	/**
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction,
	 *      org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		// do nothing
	}

}